package com.blrs.service.questionnaire.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.blrs.VO.TitleVO;
import com.blrs.common.core.domain.AjaxResult;
import com.blrs.common.exception.ServiceException;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.QuestionnaireAnswers;
import com.blrs.domain.QuestionnaireEnroll;
import com.blrs.mapper.QuestionnaireAnswersMapper;
import com.blrs.mapper.QuestionnaireEnrollMapper;
import com.blrs.service.questionnaire.IQuestionnaireTitleService;
import com.blrs.system.service.ISysDeptService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.mapper.QuestionnaireTitleMapper;
import com.blrs.domain.QuestionnaireTitle;
import org.springframework.transaction.annotation.Transactional;

/**
 * 问卷题目Service业务层处理
 * 
 * @author yang
 * @date 2023-11-28
 */
@Service
public class QuestionnaireTitleServiceImpl implements IQuestionnaireTitleService
{
    @Autowired
    private QuestionnaireTitleMapper questionnaireTitleMapper;
    @Autowired
    private QuestionnaireAnswersMapper questionnaireAnswersMapper;
    @Autowired
    private QuestionnaireEnrollMapper questionnaireEnrollMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    /**
     * 查询问卷题目
     * 
     * @param topicId 问卷题目主键
     * @return 问卷题目
     */
    @Override
    public QuestionnaireTitle selectQuestionnaireTitleByTopicId(Long topicId)
    {
        QuestionnaireTitle questionnaireTitle = questionnaireTitleMapper.selectQuestionnaireTitleByTopicId(topicId);
        questionnaireTitle.setQuestionnaireAnswersList(questionnaireAnswersMapper.selectByAnswer(topicId));
        return questionnaireTitle;
    }

    /**
     * 查询问卷题目列表
     * 
     * @param questionnaireTitle 问卷题目
     * @return 问卷题目
     */
    @Override
    public List<QuestionnaireTitle> selectQuestionnaireTitleList(QuestionnaireTitle questionnaireTitle)
    {
        List<QuestionnaireTitle> questionnaireTitles = questionnaireTitleMapper.selectQuestionnaireTitleList(questionnaireTitle);
        for (QuestionnaireTitle title : questionnaireTitles) {
            QuestionnaireAnswers questionnaireAnswers = new QuestionnaireAnswers();
            questionnaireAnswers.setTopicId(title.getTopicId());
           title.setQuestionnaireAnswersList( questionnaireAnswersMapper.selectQuestionnaireAnswersList(questionnaireAnswers));
        }
        return questionnaireTitles;
    }

    /**
     * 新增问卷题目
     * 
     * @param questionnaireTitle 问卷题目
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertQuestionnaireTitle(QuestionnaireTitle questionnaireTitle)
    {
         questionnaireTitleMapper.insertQuestionnaireTitle(questionnaireTitle);
        //通过返回的主键id新增答案数据
        for (QuestionnaireAnswers questionnaireAnswers : questionnaireTitle.getQuestionnaireAnswersList()) {
            questionnaireAnswers.setTopicId(questionnaireTitle.getTopicId());
            questionnaireAnswersMapper.insertQuestionnaireAnswers(questionnaireAnswers);
        }
        return 1;
    }

    /**
     * 修改问卷题目
     *
     * @param questionnaireTitle 问卷题目
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateQuestionnaireTitle(QuestionnaireTitle questionnaireTitle)
    {
        //查询是否还存在答案数据
        int count=questionnaireAnswersMapper.selectQuestionnaireAnswersBySolutionIdCount(questionnaireTitle.getTopicId());
        if (count==0){
            return AjaxResult.error("请至少保存一条答案");
        }
        int i = questionnaireTitleMapper.updateQuestionnaireTitle(questionnaireTitle);
        //先删除之前的答案
        questionnaireAnswersMapper.deleteQuestionnaireAnswersByTopicId(questionnaireTitle.getTopicId());
//        List<Long> collect = questionnaireTitle.getQuestionnaireAnswersList().stream().map(questionnaireAnswers -> questionnaireAnswers.getSolutionId()).collect(Collectors.toList());
//        Long[] longArray = collect.toArray(new Long[0]);
//        if (longArray.length>0){
//            questionnaireAnswersMapper.deleteQuestionnaireAnswersBySolutionIds(longArray);
//        }else {
//            questionnaireAnswersMapper.deleteQuestionnaireAnswersByTopicId(questionnaireTitle.getTopicId());
//        }
       //新增
        for (QuestionnaireAnswers questionnaireAnswers : questionnaireTitle.getQuestionnaireAnswersList()) {
            questionnaireAnswersMapper.insertQuestionnaireAnswers(questionnaireAnswers);
        }

       return AjaxResult.success();
    }

    /**
     * 批量删除问卷题目
     * 
     * @param topicIds 需要删除的问卷题目主键
     * @return 结果
     */
    @Override
    public int deleteQuestionnaireTitleByTopicIds(Long[] topicIds)
    {
        return questionnaireTitleMapper.deleteQuestionnaireTitleByTopicIds(topicIds);
    }

    /**
     * 删除问卷题目信息
     * 
     * @param topicId 问卷题目主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQuestionnaireTitleByTopicId(Long topicId)
    {
        //先删除题目对应的答案
        questionnaireAnswersMapper.deleteQuestionnaireAnswersByTopicId(topicId);
      return    questionnaireTitleMapper.deleteQuestionnaireTitleByTopicId(topicId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importExcel(List<QuestionnaireTitle> list, String id) {
        for (QuestionnaireTitle questionnaireTitle : list) {
            if (Objects.isNull(questionnaireTitle)){
                return AjaxResult.error("请导入正确的模板或者数据");
            }
            if (Objects.nonNull(questionnaireTitle.getTopicName()) && Objects.nonNull(questionnaireTitle.getQuestionType())) {
                questionnaireTitle.setQuestionnaireId(id);
                questionnaireTitleMapper.insertQuestionnaireTitle(questionnaireTitle);

                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(), questionnaireTitle.getAnswerOne(), questionnaireTitle.getAnswerOneNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(), questionnaireTitle.getAnswerTwo(), questionnaireTitle.getAnswerTwoNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(), questionnaireTitle.getAnswerThree(), questionnaireTitle.getAnswerThreeNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(), questionnaireTitle.getAnswerFour(),questionnaireTitle.getAnswerFourNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(), questionnaireTitle.getAnswerFive(), questionnaireTitle.getAnswerFiveNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(),questionnaireTitle.getAnswerSix(),questionnaireTitle.getAnswerSixNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(),questionnaireTitle.getAnswerSeven(),questionnaireTitle.getAnswerSevenNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(),questionnaireTitle.getAnswerEight(),questionnaireTitle.getAnswerEightNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(),questionnaireTitle.getAnswerNine(),questionnaireTitle.getAnswerNineNum());
                insertQuestionnaireAnswer(questionnaireTitle.getTopicId(),questionnaireTitle.getAnswerTen(),questionnaireTitle.getAnswerTenNum());
            }
        }
        return AjaxResult.success("导入成功,导入成功"+list.size()+"条数据");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveTitleByQuestionnaireId(Long[] ids, String questionnaireId) {
        //找出原有的题目列表，并把他们重新生成一份，只是对应的问卷id变化
        ArrayList<QuestionnaireTitle> questionnaireTitles = new ArrayList<>();
        for (Long id : ids) {
            QuestionnaireTitle questionnaireTitle = questionnaireTitleMapper.selectQuestionnaireTitleByTopicId(id);
            //这里先把原始数据传入答案中
            QuestionnaireAnswers questionnaireAnswers = new QuestionnaireAnswers();
            questionnaireAnswers.setTopicId(questionnaireTitle.getTopicId());
            //添加新的数据到题目对象，因为采取了事务，这时候题目还没有更新到数据库，所以查询新的题目的答案也就没有
            questionnaireTitle.setQuestionnaireId(questionnaireId);
            questionnaireTitle.setTopicId(null);
            questionnaireTitleMapper.insertQuestionnaireTitle(questionnaireTitle);
            List<QuestionnaireAnswers> questionnaireAnswers1 = questionnaireAnswersMapper.selectQuestionnaireAnswersList(questionnaireAnswers);
            questionnaireAnswers1.forEach(quest-> {
                quest.setTopicId(questionnaireTitle.getTopicId());
                quest.setSolutionId(null);
                questionnaireAnswersMapper.insertQuestionnaireAnswers(quest);
            });
        }
        return AjaxResult.success("添加成功");
    }

    @Override
    public AjaxResult selectSelectQuestionnaireTitleById(String questionnaireId) throws JsonProcessingException {
        TitleVO titleVO = new TitleVO();
        final List<QuestionnaireTitle> questionnaireTitles=questionnaireTitleMapper.selectQuestionnaireTitleListByQuestionnaireId(questionnaireId);
        for (QuestionnaireTitle questionnaireTitle : questionnaireTitles) {
            QuestionnaireAnswers questionnaireAnswers = new QuestionnaireAnswers();
            questionnaireAnswers.setTopicId(questionnaireTitle.getTopicId());
            questionnaireTitle.setQuestionnaireAnswersList( questionnaireAnswersMapper.selectQuestionnaireAnswersList(questionnaireAnswers));
        }
        titleVO.setQuestionnaireTitles(questionnaireTitles);
        titleVO.setTitleNum(questionnaireTitleMapper.selectNumTitleByQuestionnaireId(questionnaireId));
        final   QuestionnaireEnroll questionnaireEnroll = questionnaireEnrollMapper.selectEnrollByQuestionnaireIdAndByOrgId(questionnaireId, SecurityUtils.getOrgId());
        if (Objects.nonNull(questionnaireEnroll)){
            //说明该机构已经有人答题过了，直接把答题的内容展示就可以了
            ObjectMapper objectMapper = new ObjectMapper();
            List<List<Object>> result = objectMapper.readValue(questionnaireEnroll.getContent(), new TypeReference<List<List<Object>>>() {});
            titleVO.setResult(result);
            titleVO.setTotalScore(questionnaireEnroll.getQuestionnaireScore());
        }
        return AjaxResult.success(titleVO);
    }

    @Override
    public AjaxResult selectSelectQuestionnaireTitleByIdOnSend(String questionnaireId, Long orgId) throws JsonProcessingException {
        TitleVO titleVO = new TitleVO();
        final List<QuestionnaireTitle> questionnaireTitles=questionnaireTitleMapper.selectQuestionnaireTitleListByQuestionnaireId(questionnaireId);
        for (QuestionnaireTitle questionnaireTitle : questionnaireTitles) {
            QuestionnaireAnswers questionnaireAnswers = new QuestionnaireAnswers();
            questionnaireAnswers.setTopicId(questionnaireTitle.getTopicId());
            questionnaireTitle.setQuestionnaireAnswersList( questionnaireAnswersMapper.selectQuestionnaireAnswersList(questionnaireAnswers));
        }
        titleVO.setQuestionnaireTitles(questionnaireTitles);
        titleVO.setTitleNum(questionnaireTitleMapper.selectNumTitleByQuestionnaireId(questionnaireId));
        final   QuestionnaireEnroll questionnaireEnroll = questionnaireEnrollMapper.selectEnrollByQuestionnaireIdAndByOrgId(questionnaireId, orgId);
        if (Objects.nonNull(questionnaireEnroll)){
            //说明该机构已经有人答题过了，直接把答题的内容展示就可以了
            ObjectMapper objectMapper = new ObjectMapper();
            List<List<Object>> result = objectMapper.readValue(questionnaireEnroll.getContent(), new TypeReference<List<List<Object>>>() {});
            titleVO.setResult(result);
            titleVO.setTotalScore(questionnaireEnroll.getQuestionnaireScore());
        }
        return AjaxResult.success(titleVO);
    }

    private void insertQuestionnaireAnswer(Long topicId, String solutionName, String score) {
        if (StringUtils.isNotEmpty(solutionName) && StringUtils.isNotEmpty(score)) {
            QuestionnaireAnswers questionnaireAnswers = new QuestionnaireAnswers();
            questionnaireAnswers.setTopicId(topicId);
            questionnaireAnswers.setSolutionName(solutionName);
            questionnaireAnswers.setScore(Long.valueOf(score));
            questionnaireAnswersMapper.insertQuestionnaireAnswers(questionnaireAnswers);
        }
    }

}
